/**
 * 审核结果提交
 */
import { useState } from "react";
import { useResetState } from "ahooks";
import PopupApproval from "@/components/app/PopupApproval";

import { TaskStep } from "@/types/global";

type Fn = () => void;

export default (fnSuccess?: Fn, fnCancel?: Fn) => {
  // 拿到当前审批节点（如果当前用户可以审批）
  const [approverNode, setApproverNode] = useState<TaskStep>();
  // 审批节点ID
  const [itemId, setItemId, resetItemId] = useResetState<number | undefined>(
    undefined
  );
  const [state, setState, resetState] = useResetState<1 | 2 | undefined>(
    undefined
  );

  const setApproveNode = (workerId: number, approve: TaskStep) => {
    setItemId(workerId);
    setApproverNode(approve);
  };

  const handleOperate = (isSuccess?: boolean) => {
    resetState();

    // 审批提交后，重置审批节点
    if (isSuccess) {
      resetItemId();
      setApproverNode(undefined);
      fnSuccess?.();
    } else {
      fnCancel?.();
    }
  };

  // 审批组件
  const PopupApprovalInner = () =>
    !!state && (
      <PopupApproval
        state={state}
        workItemId={itemId!}
        onCancel={resetState}
        onSuccess={() => handleOperate(true)}
      />
    );

  return {
    approverNode,
    visible: !!state,
    setApproveNode,
    onCancal: () => handleOperate(),
    onApproved: () => setState(1),
    onRejected: () => setState(2),

    PopupApproval: PopupApprovalInner,
  };
};
